'use client'

import { useEffect, useState } from 'react'
import { VmsCopy } from '@/types/Model'
import { useParams, useRouter } from 'next/navigation'
import { toast } from '@/hooks/use-toast'
import ReactMarkdown from 'react-markdown'
import mermaid from 'mermaid'
import rehypeRaw from 'rehype-raw'
import remarkGfm from 'remark-gfm'
import { PrinterIcon, ArrowLeft, FileText, Download } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { cn } from '@/lib/utils'

// 初始化 Mermaid 配置
const initMermaid = () => {
  mermaid.initialize({
    startOnLoad: false,
    securityLevel: 'loose',
    theme: 'default',
    fontFamily: 'inherit',
    flowchart: {
      curve: 'basis'
    },
    themeVariables: {
      primaryColor: '#3b82f6',
      primaryTextColor: '#1f2937',
      primaryBorderColor: '#2563eb',
      lineColor: '#6b7280',
      secondaryColor: '#f3f4f6',
      tertiaryColor: '#f9fafb'
    }
  })
}

// 自定义代码块渲染组件
const CodeBlock = ({ node, inline, className, children, ...props }: any) => {
  const [svg, setSvg] = useState<string>('')
  const [error, setError] = useState<string>('')
  const [isLoading, setIsLoading] = useState(false)

  // 如果是行内代码或非 Mermaid 代码块，直接返回普通代码块
  if (inline || className !== 'language-mermaid') {
    return (
      <code
        className={cn(
          className || '',
          'bg-rose-50 dark:bg-rose-950/50 text-rose-800 dark:text-rose-200',
          'rounded-md px-2 py-1 text-sm font-mono border border-rose-200 dark:border-rose-800'
        )}
        {...props}
      >
        {children}
      </code>
    )
  }

  useEffect(() => {
    const renderDiagram = async () => {
      try {
        // 精确匹配 mermaid 代码块
        if (className !== 'language-mermaid') return

        setIsLoading(true)
        setSvg('')
        setError('')

        // 动态加载 mermaid
        mermaid.initialize({
          startOnLoad: false,
          securityLevel: 'loose',
          theme: 'default',
          themeVariables: {
            primaryColor: '#3b82f6',
            primaryTextColor: '#1f2937',
            primaryBorderColor: '#2563eb',
            lineColor: '#6b7280'
          }
        })

        // 执行渲染
        const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`
        const { svg } = await mermaid.render(id, String(children).trim())
        setSvg(svg)
      } catch (err) {
        setError(`渲染失败: ${err instanceof Error ? err.message : '未知错误'}`)
      } finally {
        setIsLoading(false)
      }
    }

    if (className === 'language-mermaid') {
      renderDiagram()
    }
  }, [children, className])

  if (error) {
    return (
      <Card className="p-4 my-6 border-red-200 bg-red-50 dark:bg-red-950/20 dark:border-red-800">
        <div className="flex items-start gap-3">
          <div className="flex-shrink-0 w-5 h-5 rounded-full bg-red-500 flex items-center justify-center mt-0.5">
            <span className="text-white text-xs font-bold">!</span>
          </div>
          <div className="flex-1">
            <div className="font-medium text-red-800 dark:text-red-200 mb-2">图表渲染错误</div>
            <div className="text-red-600 dark:text-red-300 text-sm mb-3">{error}</div>
            <pre className="p-3 bg-red-100 dark:bg-red-900/30 rounded-md text-xs overflow-auto text-red-800 dark:text-red-200 border border-red-200 dark:border-red-700">
              {children}
            </pre>
          </div>
        </div>
      </Card>
    )
  }

  if (className?.includes('language-mermaid')) {
    return (
      <Card className="mermaid-container my-8 overflow-hidden">
        {isLoading ? (
          <div className="flex items-center justify-center p-8 bg-gradient-to-br from-rose-50 to-rose-50 dark:from-rose-950/20 dark:to-rose-950/20">
            <div className="flex items-center gap-3 text-rose-600 dark:text-rose-400">
              <div className="animate-spin rounded-full h-5 w-5 border-2 border-rose-600 border-t-transparent"></div>
              <span className="text-sm font-medium">图表渲染中...</span>
            </div>
          </div>
        ) : svg ? (
          <div 
            className="bg-white dark:bg-gray-900 p-6 flex items-center justify-center min-h-[200px]"
            dangerouslySetInnerHTML={{ __html: svg }}
          />
        ) : (
          <div className="p-8 text-center text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-800/50">
            <FileText className="w-8 h-8 mx-auto mb-2 opacity-50" />
            <span className="text-sm">等待图表内容...</span>
          </div>
        )}
      </Card>
    )
  }

  return (
    <code
      className={cn(
        className,
        'bg-gray-100 dark:bg-gray-800 rounded-md px-2 py-1 text-sm font-mono'
      )}
      {...props}
    >
      {children}
    </code>
  )
}

export default function CopyEditPage() {
  const { id } = useParams()
  const router = useRouter()
  const [copy, setCopy] = useState<VmsCopy | null>(null)
  const [loading, setLoading] = useState(true)

  // 初始化 Mermaid
  useEffect(() => {
    initMermaid()
    return () => {
      mermaid.initialize({ startOnLoad: false })
    }
  }, [])

  const fetchCopy = async () => {
    try {
      const token = localStorage.getItem('token')
      const response = await fetch(`/api/copy/${id}`, {
        headers: { 'Authorization': `Bearer ${token}` }
      })

      if (!response.ok) throw new Error('获取数据失败')
      
      const data = await response.json()
      setCopy(data)
      
      toast({
        title: '数据加载成功',
        description: '内容已准备好',
      })
    } catch (error) {
      console.error('获取数据错误:', error)
      toast({
        title: '加载失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      })
      router.back()
    } finally {
      setLoading(false)
    }
  }

  const handlePrint = () => {
    // 优化打印前的准备
    const printStyles = document.createElement('style')
    printStyles.textContent = `
      @media print {
        .mermaid-container svg {
          max-width: 100% !important;
          height: auto !important;
        }
      }
    `
    document.head.appendChild(printStyles)
    
    window.print()
    
    // 清理临时样式
    setTimeout(() => {
      document.head.removeChild(printStyles)
    }, 1000)
  }

  const handleExport = () => {
    if (!copy?.rich_content) return
    
    try {
      const blob = new Blob([copy.rich_content], { 
        type: 'text/markdown;charset=utf-8' 
      })
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `${copy.title || 'untitled'}.md`
      document.body.appendChild(a)
      a.click()
      a.remove()
      window.URL.revokeObjectURL(url)
      
      toast({
        title: '导出成功',
        description: 'Markdown文件已下载',
      })
    } catch (error) {
      toast({
        title: '导出失败',
        description: '请稍后重试',
        variant: 'destructive'
      })
    }
  }

  useEffect(() => {
    if (id) fetchCopy()
  }, [id])

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-rose-50/50 via-rose-50/30 to-purple-50/50 dark:from-rose-950/20 dark:via-rose-950/10 dark:to-purple-950/20">
        <div className="flex justify-center items-center h-96">
          <Card className="p-8 bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm border-0 shadow-xl">
            <div className="flex items-center gap-4">
              <div className="animate-spin rounded-full h-8 w-8 border-3 border-rose-600 border-t-transparent"></div>
              <div>
                <div className="font-medium text-gray-900 dark:text-gray-100">加载中...</div>
                <div className="text-sm text-gray-500 dark:text-gray-400">正在获取文档内容</div>
              </div>
            </div>
          </Card>
        </div>
      </div>
    )
  }

  if (!copy) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-rose-50/50 via-rose-50/30 to-purple-50/50 dark:from-rose-950/20 dark:via-rose-950/10 dark:to-purple-950/20">
        <div className="flex justify-center items-center h-96">
          <Card className="p-8 bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm border-0 shadow-xl text-center">
            <FileText className="w-12 h-12 mx-auto mb-4 text-gray-400" />
            <div className="font-medium text-gray-900 dark:text-gray-100 mb-2">未找到相关内容</div>
            <Button 
              variant="outline" 
              onClick={() => router.back()}
              className="mt-4"
            >
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回
            </Button>
          </Card>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-rose-50/50 via-rose-50/30 to-purple-50/50 dark:from-rose-950/20 dark:via-rose-950/10 dark:to-purple-950/20">
      {/* 背景装饰 */}
      <div className="absolute top-0 left-1/4 w-96 h-96 bg-rose-200/20 dark:bg-rose-800/10 rounded-full blur-3xl pointer-events-none" />
      <div className="absolute bottom-0 right-1/4 w-96 h-96 bg-rose-200/20 dark:bg-rose-800/10 rounded-full blur-3xl pointer-events-none" />
      
      <div className="relative w-full px-4 py-8 print:py-2">
        {/* 操作栏 */}
        <div className="flex justify-between items-center mb-8 print:hidden">
          <div className="flex items-center gap-4">
            <Button 
              variant="outline" 
              onClick={() => router.back()}
              className="bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm border-gray-200/50 dark:border-gray-700/50 hover:bg-gray-50 dark:hover:bg-gray-800"
            >
              <ArrowLeft className="w-4 h-4 mr-2" />
              返回
            </Button>
            
            {copy.title && (
              <Badge 
                variant="outline" 
                className="px-3 py-1.5 bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm border-rose-200/50 dark:border-rose-800/50 text-rose-700 dark:text-rose-300"
              >
                {copy.title}
              </Badge>
            )}
          </div>
          
          <div className="flex gap-2">
            <Button
              variant="outline"
              onClick={handleExport}
              className={cn(
                "bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm transition-all duration-200",
                "border-gray-200/50 dark:border-gray-700/50 hover:bg-gray-50 dark:hover:bg-gray-800",
                "hover:scale-105 active:scale-95"
              )}
            >
              <Download className="w-4 h-4 mr-2" />
              导出MD
            </Button>
            
            <Button
              onClick={handlePrint}
              className={cn(
                "bg-gradient-to-r from-rose-600 to-rose-600 hover:from-rose-700 hover:to-rose-700",
                "text-white border-0 shadow-lg hover:shadow-xl hover:shadow-rose-500/25",
                "transition-all duration-200 hover:scale-105 active:scale-95"
              )}
            >
              <PrinterIcon className="w-4 h-4 mr-2" />
              打印
            </Button>
          </div>
        </div>

        {/* 文档内容 */}
        <Card className="bg-white/90 dark:bg-gray-900/90 backdrop-blur-sm border-0 shadow-2xl print:shadow-none print:bg-white">
          <article className={cn(
            "prose prose-slate lg:prose-lg max-w-5xl mx-auto p-8 print:prose-sm print:max-w-none print:p-4",
            "prose-headings:text-gray-900 dark:prose-headings:text-gray-100",
            "prose-p:text-gray-700 dark:prose-p:text-gray-300",
            "prose-strong:text-gray-900 dark:prose-strong:text-gray-100",
            "prose-code:text-rose-600 dark:prose-code:text-rose-400",
            "prose-pre:bg-gray-50 dark:prose-pre:bg-gray-800",
            "prose-blockquote:border-rose-500 prose-blockquote:bg-rose-50/50 dark:prose-blockquote:bg-rose-950/20",
            "prose-table:w-full prose-table:border-collapse prose-table:my-8",
            "prose-thead:bg-rose-50 dark:prose-thead:bg-rose-950/30",
            "prose-th:p-4 prose-th:border prose-th:border-gray-200 dark:prose-th:border-gray-700",
            "prose-th:text-left prose-th:font-semibold prose-th:text-gray-900 dark:prose-th:text-gray-100",
            "prose-td:p-4 prose-td:border prose-td:border-gray-200 dark:prose-td:border-gray-700",
            "prose-td:text-gray-700 dark:prose-td:text-gray-300",
            "prose-tr:hover:bg-rose-50/50 dark:prose-tr:hover:bg-rose-950/20"
          )}>
            <ReactMarkdown
              rehypePlugins={[rehypeRaw]}
              remarkPlugins={[remarkGfm]} 
              components={{
                code: CodeBlock,
                pre: ({ node, children, ...props }) => {
                  // 如果是 mermaid 代码块，只返回 children
                  if ((node?.children[0] as any)?.properties?.className?.includes('language-mermaid')) {
                    return children
                  }
                  // 其他代码块正常渲染
                  return (
                    <pre 
                      className="bg-gray-50 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4 overflow-auto"
                      {...props}
                    >
                      {children}
                    </pre>
                  )
                },
                img: ({ node, ...props }) => (
                  <img 
                    {...props} 
                    className="rounded-xl border border-gray-200 dark:border-gray-700 shadow-lg my-6 mx-auto max-w-full h-auto"
                    loading="lazy"
                  />
                ),
                h1: ({ children }) => (
                  <h1 className="text-3xl font-bold bg-gradient-to-r from-rose-600 to-rose-600 bg-clip-text text-transparent mb-6">
                    {children}
                  </h1>
                ),
                h2: ({ children }) => (
                  <h2 className="text-2xl font-semibold text-gray-900 dark:text-gray-100 mt-8 mb-4 pb-2 border-b border-gray-200 dark:border-gray-700">
                    {children}
                  </h2>
                ),
                blockquote: ({ children }) => (
                  <blockquote className="border-l-4 border-rose-500 bg-rose-50/50 dark:bg-rose-950/20 p-4 my-6 rounded-r-lg">
                    {children}
                  </blockquote>
                )
              }}
            >
              {copy.rich_content || ''}
            </ReactMarkdown>
          </article>
        </Card>
      </div>

      <style jsx global>{`
        @media print {
          @page {
            margin: 0.8cm 1.2cm;
            size: A4;
          }

          * {
            -webkit-print-color-adjust: exact !important;
            color-adjust: exact !important;
          }

          body * {
            visibility: hidden;
            font-family: 'AlibabaPuHuiTi', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
          }

          /* 确保只显示文章内容 */
          article,
          article * {
            visibility: visible;
          }

          /* 重置容器高度和背景 */
          body {
            min-height: auto !important;
            height: auto !important;
          }
          
          .min-h-screen {
            min-height: auto !important;
            height: auto !important;
          }

          /* 隐藏背景装饰元素 */
          .absolute {
            display: none !important;
          }

          article {
            position: relative;
            left: 0;
            top: 0;
            width: 100%;
            background: white !important;
            box-shadow: none !important;
            border: none !important;
            break-inside: auto;
            page-break-inside: auto;
            padding: 0.5rem !important;
            min-height: auto !important;
            height: auto !important;
            overflow: visible !important;
          }

          /* 优化分页控制 - 允许更灵活的分页 */
          h1, h2, h3, h4, h5, h6 {
            break-before: auto;
            break-after: auto; /* 改为 auto，允许在标题后分页 */
            page-break-after: auto;
            break-inside: avoid;
          }

          /* 表格和图表分页控制 - 只对大元素避免分页 */
          table {
            break-inside: avoid;
            page-break-inside: avoid;
            background: white !important;
          }
          
          /* Mermaid 图表允许分页 */
          .mermaid-container {
            margin: 1rem 0;
            break-inside: auto; /* 改为 auto，允许分页 */
            page-break-inside: auto;
          }
          
          .mermaid-container svg {
            max-width: 100% !important;
            height: auto !important;
            background: white !important;
          }

          /* 段落分页控制 - 减少孤行和寡行限制 */
          p, ul, ol {
            orphans: 2; /* 减少到2行 */
            widows: 2;  /* 减少到2行 */
            break-inside: auto;
          }

          /* 代码块允许分页 */
          pre, code {
            background: #f8f9fa !important;
            border: 1px solid #e9ecef !important;
            color: #212529 !important;
            break-inside: auto; /* 允许代码块分页 */
            page-break-inside: auto;
          }

          /* 确保最后一个元素不会强制分页 */
          article > *:last-child {
            break-after: auto !important;
            page-break-after: auto !important;
            margin-bottom: 0 !important;
          }

          /* 隐藏不必要的元素 */
          .print\\:hidden {
            display: none !important;
          }

          /* 链接显示 */
          a[href]:after {
            content: " (" attr(href) ")";
            font-size: 0.8em;
            color: #666;
          }
          
          /* 强制单页显示 - 如果内容确实只有一页 */
          @page:first {
            margin: 0.8cm 1.2cm;
          }
          
          /* 避免空白页 */
          article:after {
            content: "";
            display: block;
            height: 0;
            clear: both;
          }
        }
        
        .mermaid-container .label {
          font-family: var(--font-sans) !important;
        }

        /* Mermaid 图表样式优化 */
        .mermaid-container svg {
          font-family: 'AlibabaPuHuiTi', 'PingFang SC', sans-serif;
        }

        .mermaid-container .node rect,
        .mermaid-container .node circle,
        .mermaid-container .node ellipse,
        .mermaid-container .node polygon {
          stroke: #3b82f6;
          stroke-width: 2px;
        }

        .mermaid-container .edgePath .path {
          stroke: #6b7280;
          stroke-width: 2px;
        }
      `}</style>
    </div>
  )
}